package com.ztjava.score.service;

import java.util.Date;
import java.util.List;
import java.util.Map;

import com.jfinal.aop.Duang;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Page;
import com.xiaoleilu.hutool.date.DateUtil;
import com.ztjava.core.Constant;
import com.ztjava.core.base.BaseService;
import com.ztjava.core.client.Client;
import com.ztjava.plugin.event.EventKit;
import com.ztjava.plugin.event.EventTag;
import com.ztjava.plugin.event.core.RequestEvent;
import com.ztjava.score.model.ScoreInfo;
import com.ztjava.score.model.ScoreRecord;
import com.ztjava.score.model.ScoreSign;
import com.ztjava.score.model.ScoreType;

public class ScoreService extends BaseService {
	private static LevelService levelService = Duang.duang(LevelService.class);
	/***
	 * 新建签到
	 * @param user_id
	 * @return
	 */
	public Ret insertSign(Integer user_id){
		String today = DateUtil.date().toString("yyyy-MM-dd");
		String yesterday = DateUtil.offsetDay(new Date(), -1).toString("yyyy-MM-dd");
		if(getSign(today,user_id)!=null){
			return Ret.create(Constant.RESULT, Constant.ERROR).set(Constant.MESSAGE, "今天已签过到了。");
		}
		ScoreSign yesterdaySign = getSign(yesterday, user_id);
		ScoreSign scoreSign = new ScoreSign();
		scoreSign.set("sign_date", today);
		if(yesterdaySign!=null){
			scoreSign.set("lianxu", yesterdaySign.getInt("lianxu")+1);
		}else {
			scoreSign.set("lianxu", 1);
		}
		scoreSign.set("create_user", user_id);
		scoreSign.save();
		List<Ret> retList = EventKit.postRemote(EventTag.SCORE_SIGN, new RequestEvent(scoreSign.toJson()));
		String message = "";
		for(int i=0;i<retList.size();i++){
			message = message + retList.get(i).getStr(Constant.MESSAGE);
			if(i<(retList.size()-1)){
				message = message+ ",";
			}
		}
		return Ret.create(Constant.RESULT,Constant.SUCCESS).set("lianxu", scoreSign.getInt("lianxu")).set(Constant.MESSAGE, message);
	}
	/***
	 * 查询签到
	 * @param date
	 * @param user_id
	 * @return
	 */
	public ScoreSign getSign(String date,Integer user_id){
		return ScoreSign.dao.findFirst("select * from "+ScoreSign.tablename+" where sign_date=? and create_user=?",date,user_id);
	}
	public Page<ScoreType> getTypePage(Client client ,Map<String,String[]> paramMap){
		String[][] param = new String[][]{
				new String[]{"name",like,"name"}
				,new String[]{"code",like,"code"}
				,new String[]{"enable_flag",eq,"enable_flag"}
		};
		Page<ScoreType> pd = ScoreType.dao.paginate(
				getParaToInt(paramMap, client.getPageNumber(), 1), 
				getParaToInt(paramMap,client.getPageSize(),20),
				"select *","from "+ScoreType.tablename+" where 1=1 "+whereSql(paramMap, param)
					+orderby(client, paramMap),whereParam(paramMap, param));
		changeBasedata(pd.getList()		, new String[]{"enable_flag","ENABLE_FLAG"});
		return pd;
	}
	public Page<ScoreRecord> getRecordPage(Client client ,Map<String,String[]> paramMap){
		String[][] param = new String[][]{
				new String[]{"user_id",eq,"user_id"}
		};
		Page<ScoreRecord> pd = ScoreRecord.dao.paginate(
				getParaToInt(paramMap, client.getPageNumber(), 1),
				getParaToInt(paramMap,client.getPageSize(),20),
				"select *","from "+ScoreRecord.tablename+" where 1=1 "+whereSql(paramMap, param)
					+orderby(client, paramMap),whereParam(paramMap, param));
		changeBasedata(pd.getList()		, new String[]{"type_id","SCORE_TYPE"});
		changeUser(pd.getList(),new String[]{"user_id","name"});
		return pd;
	}
	public boolean checkScore(Integer user_id,String code,Integer score){
		ScoreInfo scoreInfo = getUserScoreInfo(user_id, code);
		Ret ret = new Ret();
		if(scoreInfo==null){
			ret.set(Constant.RESULT, Constant.ERROR);
			ret.set(Constant.MESSAGE, "找不到积分类型");
			return false;
		}
		if(scoreInfo.getInt("score")<score){
			ret.set(Constant.RESULT, Constant.ERROR);
			ret.set(Constant.MESSAGE, "积分不足！");
			return false;
		}
		return true;
	}
	
	/***
	 * 更新用户积分
	 * @param user_id
	 * @param type
	 * @param score
	 * @param remark
	 * @param create_user
	 * @return
	 */
	public Ret updateScore(Integer user_id,String code,Integer score,String remark,Integer create_user){
		ScoreInfo scoreInfo = getUserScoreInfo(user_id, code);
		Ret ret = new Ret();
		if(scoreInfo==null){
			ret.set(Constant.RESULT, Constant.ERROR);
			ret.set(Constant.MESSAGE, "找不到积分类型");
			return ret;
		}
		if(score<0){
			if(scoreInfo.getInt("score")<(-score)){
				ret.set(Constant.RESULT, Constant.ERROR);
				ret.set(Constant.MESSAGE, "积分不足！");
				return ret;
			}
		}
		Integer result = scoreInfo.getInt("score")+score;
		scoreInfo.set("score", result).update();
		ScoreRecord scoreRecord = new ScoreRecord();
		scoreRecord.set("user_id", user_id);
		scoreRecord.set("type_id", scoreInfo.getInt("type_id"));
		scoreRecord.set("score", score);
		scoreRecord.set("remark", remark);
		scoreRecord.set("create_user", create_user);
		scoreRecord.save();
		//如果此积分关联等级
		levelService.updateUserLevel( scoreInfo.getInt("type_id"), user_id,result);
		
		ret.set(Constant.RESULT, Constant.SUCCESS);
		ret.set(Constant.MESSAGE, "更新成功！");
		return ret;
	}

	/***
	 * 获取用户积分情况
	 * @param user_id
	 * @param code
	 * @return
	 */
	public ScoreInfo getUserScoreInfo(Integer user_id,String code){
		if(code==null||code.equals("")){
			return null;
		}
		ScoreType scoreType = ScoreType.dao.findFirst("select * from "+ScoreType.tablename+" where enable_flag='T' and code=?",code);
		if(scoreType==null){
			return null;
		}
		ScoreInfo scoreInfo = ScoreInfo.dao.findFirst("select * from "+ScoreInfo.tablename+" where type_id=? and user_id=?",scoreType.getInt("id"),user_id);
		if(scoreInfo==null){
			scoreInfo = new ScoreInfo();
			scoreInfo.set("type_id",scoreType.getInt("id"));
			scoreInfo.set("user_id",user_id);
			scoreInfo.set("score", 0);
			scoreInfo.save();
		}
		return scoreInfo;
	}
	
	public List<ScoreInfo> getUserScoreInfoList(Integer user_id){
		return ScoreInfo.dao.find("select A.*,(case when B.score is null then 0 else B.score end) as score from "+ScoreType.tablename+" A left join (select * from "+ScoreInfo.tablename+" where user_id="+user_id+") B ON A.id=B.type_id order by A.id asc");
		
	}
	
	/*************
	 *Sign分页
	**************/
	public Page<ScoreSign> getSignPage(Client client,Map<String,String[]> paramMap){
		String[][] param = new String[][]{
		new String[]{"create_user",eq,"create_user"}			};
		Page<ScoreSign> pd = ScoreSign.dao.paginate(
				getParaToInt(paramMap, client.getPageNumber(), 1), 
				getParaToInt(paramMap,client.getPageSize(),20),
				"select *","from "+ScoreSign.tablename+" where 1=1 " 				
				+ whereSql(paramMap,param)
				+ orderby(client, paramMap),whereParam(paramMap, param));
		changeUser(pd.getList(),new String[]{"create_user","name"});
		return pd;
	}

}
